<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>demo01</title>
</head>

<body>
  <div>01</div>
  <div>02</div>
  <div>03</div>
  <div>04</div>
  <div>05</div>
  <script>
    var nodes = document.getElementsByTagName('div');

    // for (var i = 0, len = nodes.length; i < len; i++) {
    //   nodes[i].onclick = function () {
    //     alert(i);
    //   }
    // }

    for (var i = 0, len = nodes.length; i < len; i++) {
      (function(i) {
        nodes[i].onclick = function () {
          alert(i);
        }
      })(i)
    }
  </script>
</body>

</html>